package app.maker.controleur;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import app.maker.error.UserException;
import app.maker.metier.entite.Authentification;
import app.maker.service.UserService;

/**
 * Servlet implementation class Connexion
 */
public class Connexion extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Connexion() {
		super();
		this.userService = new UserService();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String passwd = request.getParameter("password");
		Authentification authentification = new Authentification();
		authentification.setLogin(login);
		authentification.setMdp(passwd);
		Authentification result = null;
		try {
			result = userService.connect(authentification);
			if (result.getEtat()) {
				if (result.getStatut() == 1) {
					HttpSession session = request.getSession(true);
					session.setAttribute("id", result.getId());
					session.setAttribute("role", result.getRole());
					session.setAttribute("login", result.getLogin());
					if (result.getRole() == 0)
						response.sendRedirect(request.getContextPath()
								+ "/maker/admin/index.jsp");
					else
						response.sendRedirect(request.getContextPath()
								+ "/maker/public/index.jsp");
				} else
					response.sendRedirect(request.getContextPath()
							+ "/maker/login.jsp");
			} else
				response.sendRedirect(request.getContextPath() + "/maker/login.jsp");
		} catch (UserException e) {
			e.printStackTrace();
		}
	}

}
